﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace RoboticArmTestHost
{
    internal class MES
    {
        private string baseUrl;
        private HttpClient client;
        private string usercode;
        private string password;

        public MES(string baseUrl, string usercode, string password)
        {
            this.baseUrl = baseUrl;
            this.client = new HttpClient();
            this.usercode = usercode;
            this.password = password;
        }

        public async Task<bool> Login()
        {
            string url = baseUrl + "/Login/doAction";
            var payload = new
            {
                usercode = usercode,
                password = password
            };
            var json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.PostAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var data = JsonConvert.DeserializeObject<dynamic>(responseContent);
                    if (data.errorcode == 0)
                    {
                        Console.WriteLine("MES 登录成功");
                        return true;
                    }
                    else
                    {
                        Console.WriteLine("MES 登录失败");
                        return false;
                    }
                }
                else
                {
                    Console.WriteLine("MES 登录异常");
                    return false;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Login request failed: {e.Message}");
                return false;
            }
        }

        public async Task<dynamic> GetWorkshop()
        {
            string url = baseUrl + "/Content/passstation/Wip_Normal_panel.aspx?Oper=get_workshop";
            var payload = new
            {
                user = usercode
            };
            var json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(responseContent);
                }
                else
                {
                    Console.WriteLine($"Get workshop request failed: {response.StatusCode}");
                    throw new Exception($"Get workshop request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Get workshop request failed: {e.Message}");
                throw;
            }
        }

        public async Task<dynamic> GetLine(string workshop_id)
        {
            string url = baseUrl + "/Content/passstation/Wip_Normal_panel.aspx?Oper=get_scx_bywork";
            var payload = new
            {
                user = usercode,
                work_code = workshop_id
            };
            var json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.PostAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(responseContent);
                }
                else
                {
                    Console.WriteLine($"Get line request failed: {response.StatusCode}");
                    throw new Exception($"Get line request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Get line request failed: {e.Message}");
                throw;
            }
        }

        public async Task<dynamic> GetStation(string line_id)
        {
            string url = baseUrl + "/Content/passstation/Wip_Normal_panel.aspx?Oper=get_gw";
            var payload = new
            {
                user = usercode,
                sxc_code = line_id
            };
            var json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(responseContent);
                }
                else
                {
                    Console.WriteLine($"Get station request failed: {response.StatusCode}");
                    throw new Exception($"Get station request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Get station request failed: {e.Message}");
                throw;
            }
        }

        public async Task<dynamic> GetProcess(string station_id)
        {
            string url = baseUrl + "/Content/passstation/Wip_Normal_panel.aspx?Oper=get_gx";
            var payload = new
            {
                gw_code = station_id
            };
            var json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(responseContent);
                }
                else
                {
                    Console.WriteLine($"Get process request failed: {response.StatusCode}");
                    throw new Exception($"Get process request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Get process request failed: {e.Message}");
                throw;
            }
        }

        public async Task<dynamic> QueryWorkOrder(string lot_no, string station_name, string step_name, string line = null)
        {
            string url = baseUrl + "/Content/passstation/Wip_Normal_panel.aspx?Oper=getLotInfo";
            var parameters = new Dictionary<string, string>
            {
                { "lotNo", lot_no },
                { "stationName", station_name },
                { "stepName", step_name },
                { "user", usercode },
                { "line", line }
            };
            var queryString = string.Join("&", parameters.Select(p => $"{p.Key}={Uri.EscapeDataString(p.Value)}"));
            url += "?" + queryString;

            try
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(responseContent);
                }
                else
                {
                    Console.WriteLine($"Query work order request failed: {response.StatusCode}");
                    throw new Exception($"Query work order request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Query work order request failed: {e.Message}");
                throw;
            }
        }

        public async Task<dynamic> QueryPlan(string lot_name, string line, string station_name)
        {
            string url = baseUrl + "/Content/passstation/Wip_Normal_panel.aspx?Oper=query2";
            var parameters = new Dictionary<string, string>
            {
                { "LOT_NAME", lot_name },
                { "line", line },
                { "stationName", station_name },
                { "user", usercode }
            };
            var queryString = string.Join("&", parameters.Select(p => $"{p.Key}={Uri.EscapeDataString(p.Value)}"));
            url += "?" + queryString;

            try
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(responseContent);
                }
                else
                {
                    Console.WriteLine($"Query plan request failed: {response.StatusCode}");
                    throw new Exception($"Query plan request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Query plan request failed: {e.Message}");
                throw;
            }
        }

        public async Task<dynamic> CheckPass(string lot_name, string serials, string station_name, string step_name = null, int scan_type = 99)
        {
            string url = baseUrl + "/WIP/check2";
            var payload = new
            {
                lotName = lot_name,
                inputSerials = serials,
                station_name = station_name,
                userID = usercode,
                stepName = step_name,
                SCAN_TYPE = scan_type
            };
            var json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.PostAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(responseContent);
                }
                else
                {
                    Console.WriteLine($"Check pass request failed: {response.StatusCode}");
                    throw new Exception($"Check pass request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Check pass request failed: {e.Message}");
                throw;
            }
        }

        public async Task<Tuple<int, string>> PassStation(string lot_name, string serials, string station_name, string step_name = null, int scan_type = 99)
        {
            string url = baseUrl + "/WIP/Complete2";
            var payload = new
            {
                lotName = lot_name,
                inputSerials = serials,
                station_name = station_name,
                userID = usercode,
                stepName = step_name,
                SCAN_TYPE = scan_type
            };
            var json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.PostAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<dynamic>(responseContent);
                    return new Tuple<int, string>((int)result.errorcode, (string)result.content);
                }
                else
                {
                    Console.WriteLine($"Pass station request failed: {response.StatusCode}");
                    throw new Exception($"Pass station request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Pass station request failed: {e.Message}");
                throw;
            }
        }

        public async Task<dynamic> GetBindingInfo(string serial_number)
        {
            string url = baseUrl + "/Content/passstation/Wip_Normal_panel.aspx?Oper=get_bind_info";
            var payload = new
            {
                serialNumber = serial_number
            };
            var json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(responseContent);
                }
                else
                {
                    Console.WriteLine($"Get binding info request failed: {response.StatusCode}");
                    throw new Exception($"Get binding info request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Get binding info request failed: {e.Message}");
                throw;
            }
        }

        public async Task<dynamic> GetBindingInfo2(string id)
        {
            string url = baseUrl + "/Content/datasearch/query.aspx?Oper=bindbarcode";
            url += $"&text={Uri.EscapeDataString(id)}";

            try
            {
                var response = await client.PostAsync(url, null);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<dynamic>(responseContent);
                }
                else
                {
                    Console.WriteLine($"Get binding info request failed: {response.StatusCode}");
                    throw new Exception($"Get binding info request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Get binding info request failed: {e.Message}");
                throw;
            }
        }

        public async Task<dynamic> UnbindingInfo(string line_name, string workstation_name, string process_name, string sn, string lot_name)
        {
            string url = baseUrl + "/content/unlink/Untying.aspx?action=get_scx";
            try
            {
                var response = await client.PostAsync(url, null);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var line_list = JsonConvert.DeserializeObject<dynamic>(responseContent);
                    Console.WriteLine("线体:");
                    Console.WriteLine(line_list);
                    string line = null;
                    foreach (var item in line_list)
                    {
                        if ((string)item.FullName == line_name)
                        {
                            line = (string)item.Code;
                            break;
                        }
                    }

                    url = baseUrl + $"/content/unlink/Untying.aspx?action=get_gw&sxc_code={Uri.EscapeDataString(line)}";
                    response = await client.PostAsync(url, null);
                    if (response.IsSuccessStatusCode)
                    {
                        var workstation_list = JsonConvert.DeserializeObject<dynamic>(responseContent);
                        Console.WriteLine("工位：");
                        Console.WriteLine(workstation_list);
                        string workstation = null;
                        foreach (var item in workstation_list)
                        {
                            if ((string)item.FullName == workstation_name)
                            {
                                workstation = (string)item.Code;
                                break;
                            }
                        }

                        url = baseUrl + $"/content/unlink/Untying.aspx?action=get_gx&gw_code={Uri.EscapeDataString(workstation)}";
                        response = await client.PostAsync(url, null);
                        if (response.IsSuccessStatusCode)
                        {
                            var process_list = JsonConvert.DeserializeObject<dynamic>(responseContent);
                            Console.WriteLine(process_list);
                            string process = null;
                            foreach (var item in process_list)
                            {
                                if ((string)item.FullName == process_name)
                                {
                                    process = (string)item.Code;
                                    break;
                                }
                            }
                            Console.WriteLine("工序：");
                            Console.WriteLine(process_list);

                            url = baseUrl + $"/content/unlink/Untying.aspx?action=sn_check&SN={Uri.EscapeDataString(sn)}&Lot_name={Uri.EscapeDataString(lot_name)}&key={Guid.NewGuid()}";
                            response = await client.PostAsync(url, null);
                            if (response.IsSuccessStatusCode)
                            {
                                var result = JsonConvert.DeserializeObject<dynamic>(responseContent);
                                Console.WriteLine("查询：");
                                Console.WriteLine(result);
                                if ((int)result.state != 100)
                                {
                                    return null;
                                }

                                url = baseUrl + "/content/unlink/Untying.aspx?action=untying_lots&key=" + Guid.NewGuid();
                                var payload = new
                                {
                                    Rows = JsonConvert.SerializeObject(new[]
                                    {
                                        new
                                        {
                                            SERIAL_NUMBER = sn,
                                            ASSEMBLY_SN = sn,
                                            LOT_ID = (string)result.data[0].LOT_ID,
                                            ASSEMBLY_TIME = (string)result.data[0].ASSEMBLY_TIME
                                        }
                                    }),
                                    ROUTE_STEP_ID = (string)result.data[0].ROUTE_STEP_ID,
                                    uname = usercode,
                                    txtStationName = workstation,
                                    routeStepName = process,
                                    routeStep_ID = (string)result.data[0].ROUTE_STEP_ID
                                };
                                var json = JsonConvert.SerializeObject(payload);
                                var content = new StringContent(json, Encoding.UTF8, "application/json");

                                response = await client.PostAsync(url, content);
                                if (response.IsSuccessStatusCode)
                                {
                                    var unbinding_result = JsonConvert.DeserializeObject<dynamic>(responseContent);
                                    return unbinding_result;
                                }
                                else
                                {
                                    Console.WriteLine($"Get unbinding info request failed: {response.StatusCode}");
                                    throw new Exception($"Get unbinding info request failed: {response.StatusCode}");
                                }
                            }
                            else
                            {
                                Console.WriteLine($"Get result info request failed: {response.StatusCode}");
                                throw new Exception($"Get result info request failed: {response.StatusCode}");
                            }
                        }
                        else
                        {
                            Console.WriteLine($"Get process info request failed: {response.StatusCode}");
                            throw new Exception($"Get process info request failed: {response.StatusCode}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"Get workstation info request failed: {response.StatusCode}");
                        throw new Exception($"Get workstation info request failed: {response.StatusCode}");
                    }
                }
                else
                {
                    Console.WriteLine($"Get line info request failed: {response.StatusCode}");
                    throw new Exception($"Get line info request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Get unbinding info request failed: {e.Message}");
                throw;
            }
        }

/*
        public async Task<dynamic> RepairInfo(string line_name, string workstation_name, string process_name, string sn, string cause, string remark)
        {
            string url = baseUrl + "//Repair/GetRepairInfo";
            var payload = new
            {
                serialNumber = sn,
                lineName = line_name
            };
            var json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await client.PostAsync(url, content);
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonConvert.DeserializeObject<dynamic>(responseContent);
                    if ((int)result.errorcode != 0)
                    {
                        return null;
                    }

                    url = baseUrl + "//Repair/Repair";
                    payload = new
                    {
                        failStep = (string)result.info.gx,
                        lotNo = (string)result.info.lotName,
                        redirect2StepName = (string)result.info.gx,
                        stepName = process_name,
                        serialNumber = sn,
                        stationName = workstation_name,
                        repairUserID = usercode,
                        defects = new[]
                        {
                                    new
                                    {
                                        defectID = (string)result.info.defect[0].DEFECT_ID,
                                        defectType = (string)result.info.defect[0].DEFECT_TYPE,
                                        defectCode = (string)result.info.defect[0].DEFECT_LABEL,
                                        defectLocation = (string)result.info.defect[0].DEFECT_LOCATION,
                                        defectPartNumber = sn,
                                        repairAction = "1",
                                        quantity = 0,
                                        repariRemark = remark,
                                        defectAnalysis = "",
                                        defectCategory = cause,
                                        defectTypeInfo = "",
                                        dutyDept = "",
                                        scrapChecked = "0"
                                    }
                                },
                        reels = new object[0],
                        assemblys = new object[0],
                        replaceSerials = new object[0],
                        historySerials = new object[0],
                        repairDefects = new[]
                        {
                                    new
                                    {
                                        id = (string)result.info.defect[0].DEFECT_ID,
                                        DEFECT_TYPE = (string)result.info.defect[0].DEFECT_TYPE,
                                        DEFECT_LABEL = (string)result.info.defect[0].DEFECT_LABEL,
                                        DEFECT_LOCATION = (string)result.info.defect[0].DEFECT_LOCATION,
                                        SERIAL_NUMBER = sn
                                    }
                                }
                    };
                    var jsonStr = JsonConvert.SerializeObject(payload, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeNonAscii });
                    var inputSerials = Uri.EscapeDataString(jsonStr);
                    var parameters = new Dictionary<string, string>
                            {
                                { "inputSerials", inputSerials }
                            };
                    var queryString = string.Join("&", parameters.Select(p => $"{p.Key}={p.Value}"));
                    url += "?" + queryString;

                    response = await client.PostAsync(url, null);
                    if (response.IsSuccessStatusCode)
                    {
                        var repairResult = await response.Content.ReadAsStringAsync();
                        return JsonConvert.DeserializeObject<dynamic>(repairResult);
                    }
                    else
                    {
                        Console.WriteLine($"Get repair info request failed: {response.StatusCode}");
                        throw new Exception($"Get repair info request failed: {response.StatusCode}");
                    }
                }
                else
                {
                    Console.WriteLine($"Get result info request failed: {response.StatusCode}");
                    throw new Exception($"Get result info request failed: {response.StatusCode}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Get repair info request failed: {e.Message}");
                throw;
            }
        }*/
    }
}

